'''
Created on Aug 18, 2009

@author: mkiyer
'''

from veggie.genome.chrom import get_chrom_names
import logging
import sys
import h5py
import numpy as np

def compare_hdf5(file1, file2):
    
    h51 = h5py.File(file1, 'r')
    h52 = h5py.File(file2, 'r')
    
    for group_name, group1 in h51.items():
        print group_name
        group2 = h52[group_name]
        for dset_name, d1 in group1.items():
            print dset_name
            d2 = group2[dset_name]
            start = 0
            for end in xrange(10000, d1.len(), 10000):
                print 'pos', start, end
                a = d1[start:end]
                b = d2[start:end]
                if not np.array_equal(a, b):
                    print file1, start, end, a
                    print file2, start, end, b
                    sys.exit(0)
                start = end                            
            a = d1[start:d1.len()]
            b = d2[start:d2.len()]
            if not np.array_equal(a, b):
                print file1, start, end, a
                print file2, start, end, b
            

    
def combine_hdf5(files, outfile):
    logging.basicConfig(level=logging.DEBUG)

    h5out = h5py.File(outfile, 'w')
    for chrom in get_chrom_names():        
        for file in files:
            logging.debug('opening file: %s for reading' % file)
            f = h5py.File(file, 'r')
            if chrom in f:
                if not chrom in h5out:
                    logging.debug('    creating new dataset for chrom %s', chrom)
                    chrom_dset = h5out.create_dataset(chrom, data=np.array(f[chrom]), compression='szip', compression_opts=('nn', 16))
                else:
                    logging.debug('    adding data for chrom %s', chrom)
                    h5out[chrom] += f[chrom]
            f.close()
    h5out.close()

if __name__ == '__main__':
    #   combine_hdf5(sys.argv[1:-1], sys.argv[-1])
    compare_hdf5(sys.argv[1], sys.argv[2])
    
